import { create } from 'zustand'
import { getItem } from '@/utils/storage'
import { creatRoute } from '../router/hooks/usePermissionRoute'
import { RouteObject } from 'react-router-dom'

import { loginRequest } from '@/router/components/AuthGuard'

import { UserType } from '#/store'
import { StorageEnum } from '#/enum'

type UserStore = {
  userInfo: Partial<UserType>
  permissionsRoute: RouteObject[]
  actions: {
    setUserInfo: (userInfo: UserType) => void
    setPermissions: () => void
    clearUserInfo: () => void
  }
}

export const useUserStore = create<UserStore>(set => {
  return {
    userInfo: getItem(StorageEnum.User) || {},
    permissionsRoute: [],
    actions: {
      setUserInfo: (userInfo: UserType) => {
        set({ userInfo })
      },
      setPermissions: async () => {
        const permissions = await loginRequest()
        set(state => {
          return { userInfo: { ...state.userInfo, permissions }, permissionsRoute: creatRoute(permissions) as RouteObject[] }
        })
      },
      clearUserInfo: () => {
        set({ userInfo: {} })
      }
    }
  }
})

export const useUserInfo = () => useUserStore(state => state.userInfo)
export const usePermissionsRoute = () => useUserStore(state => state.permissionsRoute)
export const useUserActions = () => useUserStore(state => state.actions)
